package com.homework;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

public class PlainOioServer {

    public void server(int port) throws IOException{

        final ServerSocket socket = new ServerSocket(port);

        try{
            while (true){
                final Socket clientSocket = socket.accept();
                System.out.println("Accepted connection from "+clientSocket);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OutputStream outputStream;
                        try{
                            outputStream = clientSocket.getOutputStream();
                            outputStream.write("Hi!\r\n".getBytes(Charset.forName("UTF-8")));
                            outputStream.flush();
                            clientSocket.close();
                        }catch (IOException e){
                            e.printStackTrace();
                            try{
                                clientSocket.close();
                            }catch (IOException ex){
                                ex.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
